//
// This file is part of cpp-lib, a library of C++ functions and classes.
// Cpp-lib is copyright (C) 2004 and onwards, The CPL Interest Group.
// 
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version.
// 
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
// General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public License
// along with this library (see the file COPYING); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
// 02111-1307  USA
//
// $Id$
//

//
// This define necessary according to MSN documentation on
// CreateWaitableTimer().
//

#define _WIN32_WINNT 0x0400

#include <cmath>
#include <iostream>

#include "cpp-lib/util.h"
#include "cpp-lib/windows/wrappers.h"

#include "cpp-lib/realtime.h"

using namespace cpl::util ;


cpl::util::realtime_scheduler::realtime_scheduler( double const& dt ) {

  always_assert( dt > 0 ) ;

  LARGE_INTEGER dueTime ;
  dueTime.QuadPart = -1 ;

  const LONG period = static_cast< LONG >( std::floor( dt * 1000 + 0.5 ) ) ;

  timer.reset( CreateWaitableTimer( 0 , 0 , 0 ) ) ;

  if( !timer.valid() )
  { cpl::detail_::last_error_exception( "CreateWaitableTimer()" ) ; }

  if( !SetWaitableTimer( timer.get() , &dueTime , period , 0 , 0 , 0 ) )
  { cpl::detail_::last_error_exception( "SetWaitableTimer()"    ) ; }

}


double cpl::util::realtime_scheduler::wait_next() {

  if( WAIT_OBJECT_0 != WaitForSingleObject( timer.get() , INFINITE ) )
  { cpl::detail_::last_error_exception( "WaitForSingleObject()" ) ; }

  return time() ;

}
